﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

using PowerCreator.LMS.Common.Script;
using PowerCreator.LMS.Web.Course;
using PowerCreator.LMS.Course.Entity;
using PowerCreator.LMS.Web.Catalog;
using PowerCreator.LMS.ViewQuery;

public partial class sysadmin_CourseManager_Course :PowerCreator.LMS.Web.Base.WebBasePage
{
//******test****//

    long er = Environment.TickCount;
//******test****//
   protected  Course opCourse = new Course();
    Catalog opCatalog = new Catalog();
    ViewQuery opViewQuery = new ViewQuery();
    CatalogCourse opCatalogCourse = new CatalogCourse();
    PowerCreator.LMS.Web.Project.ProjectResource objProjectResource = new PowerCreator.LMS.Web.Project.ProjectResource();


    private string _SQL_Catalog_Course = "select "
        + " tcc.CatalogcouID,tg.CatalogId,tg.CatalogName,tc.Course_Id,tc.CourseName,tc.CourseMostlyTeacherName,tc.CourseIsCompulsory,tc.CourseState ,tc.CourseResourceNum"
        + " from TCatalogCourse tcc ,"
        + "TO_Course tc,TCatalog tg where tc.xueke=tg.CatalogId and tcc.FKCatalogcouCourseID=tc.Course_Id and";
       // + " TO_Course tc left join TCatalog tg on tc.xueke=tg.CatalogId where tcc.FKCatalogcouCourseID=tc.Course_Id and  ";

    private PowerCreator.LMS.Web.DL.User.LoginEntity login = new PowerCreator.LMS.Web.DL.User.LoginEntity();
    private string url = "../login.aspx";
    
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Diagnostics.Debug.Write("\n Page_Load Star..." + (Environment.TickCount - er) + "\n");
        if (!IsPostBack)
        {
            //btnDel.Visible = IsLicensed("DelCourse");
            ViewState["SearchType"] = "0";  //0简单搜索1高级搜索
            ViewState["OrderList"] = "";//排序
            ViewState["OrderType"] = " desc ";//排序方式
            BinderCourseType();
            InitPage();
            BinderCatalog();

            System.Diagnostics.Debug.Write("\n BinderCatalog() End..." + (Environment.TickCount - er) + "\n");

            string search = GetSearch();
            BinderPager(search);
            System.Diagnostics.Debug.Write("\n BinderPager() End..." + (Environment.TickCount - er) + "\n");
            BinderRPT(search, 1);
            System.Diagnostics.Debug.Write("\n BinderRPT() End..." + (Environment.TickCount - er) + "\n");
            if (CheckUser())
            {
                btnLock.Enabled = true;
                btnAuditing.Enabled = true;
                btnDel.Enabled = true;
                btn_Add.Enabled = true;
                btn_AddFKCourse.Enabled = true;
            }
            else
            {
                btnLock.Enabled = false;
                btnAuditing.Enabled = false;
                btnDel.Enabled = false;
                btn_Add.Enabled = false;
                btn_AddFKCourse.Enabled = false;
            }
        }
        System.Diagnostics.Debug.Write("\n Page_Load End..." + (Environment.TickCount - er) + "\n");
    }
    private bool CheckUser()
    {
        bool rt = false;
        if (Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO] == null)
        {
            Script.RedirectNewUrl(url);
        }
        else
        {
            login = (PowerCreator.LMS.Web.DL.User.LoginEntity)Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO];
            if (login == null)
            {
                Script.RedirectNewUrl(url);
            }
            else
            {
                if (login.VOAdvancedUser == null)
                {
                    Script.RedirectNewUrl(url);
                }
                else if (login.VOAdvancedUser.AUserGroup == 1 || login.VOAdvancedUser.AUserGroup == 2)
                {
                    rt = true;
                }

            }
        }

        return rt;

    }
    protected override void InitPage()
    {
        System.Diagnostics.Debug.Write("\n initPageStar...." + (Environment.TickCount - er) + "\n");

        lbl_InfoTitle.Text = GetLanageValueByKey("lbl_Course_InfoTitle", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_CourseName.Text = GetLanageValueByKey("lbl_Course_Name", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_CourseMostlyTeacherName.Text = GetLanageValueByKey("lbl_Course_CourseMostlyTeacherName", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_Catalog.Text = GetLanageValueByKey("lbl_Course_Catalog", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_CourseType.Text = GetLanageValueByKey("lbl_Course_CourseType", PowerCreator.LMS.Language.LanagetItemType.Page);

        chkAll.Text = GetLanageValueByKey("RoleUser_rdbtn_YesNoAll", PowerCreator.LMS.Language.LanagetItemType.Page);
        chkCancel.Text = GetLanageValueByKey("SetBaseAction_rdbtn_All", PowerCreator.LMS.Language.LanagetItemType.Page);

        btn_Search.Text = GetLanageValueByKey("btn_Course_Search", PowerCreator.LMS.Language.LanagetItemType.Page);
        btn_Add.Text = GetLanageValueByKey("btn_Course_Add", PowerCreator.LMS.Language.LanagetItemType.Page);
        btn_AddFKCourse.Text = GetLanageValueByKey("btn_Course_AddFKCourse", PowerCreator.LMS.Language.LanagetItemType.Page);
        btnLock.Text = GetLanageValueByKey("btn_Course_btnLock", PowerCreator.LMS.Language.LanagetItemType.Page);
        btnAuditing.Text = GetLanageValueByKey("btn_Course_btnAuditing", PowerCreator.LMS.Language.LanagetItemType.Page);
        btnDel.Text = GetLanageValueByKey("btn_Course_btnDel", PowerCreator.LMS.Language.LanagetItemType.Page);
        btn_SortSearch.Text = GetLanageValueByKey("btn_Course_Search", PowerCreator.LMS.Language.LanagetItemType.Page);
        lbl_Search.Text = GetLanageValueByKey("btn_ManagerQuestion_highSearch", PowerCreator.LMS.Language.LanagetItemType.Page);
        btnDel.Attributes.Add("onClick", "javascript:return confirm('确定删除此记录？');");

        System.Diagnostics.Debug.Write("\n Base..initPageEnd...." + (Environment.TickCount - er) + "\n");
        base.InitPage();
        System.Diagnostics.Debug.Write("\n initPageEnd...." + (Environment.TickCount - er) + "\n");
    }
    protected void BinderCourseType()
    {
        ListItem li = new ListItem();
        li.Text = GetLanageValueByKey("Course_db_d0", PowerCreator.LMS.Language.LanagetItemType.Page);
        li.Value = "0";

        ListItem li0 = new ListItem();
        li0.Text = GetLanageValueByKey("Course_db_d1", PowerCreator.LMS.Language.LanagetItemType.Page);
        li0.Value = "1";
        ListItem li1 = new ListItem();
        li1.Text = GetLanageValueByKey("Course_db_d2", PowerCreator.LMS.Language.LanagetItemType.Page);
        li1.Value = "2";

        ListItem li2 = new ListItem();
        li2.Text = GetLanageValueByKey("Course_db_d3", PowerCreator.LMS.Language.LanagetItemType.Page);
        li2.Value = "3";

        ddl_CourseType.Items.Add(li);
        ddl_CourseType.Items.Add(li0);
        ddl_CourseType.Items.Add(li1);
        ddl_CourseType.Items.Add(li2);
    }

    protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
        {
            LinkButton lnkbtn_editor = (LinkButton)e.Item.FindControl("lnkbtn_editor");
            LinkButton lnkbtn_del = (LinkButton)e.Item.FindControl("lnkbtn_del");
            LinkButton lnkbtn_check = (LinkButton)e.Item.FindControl("lnkbtn_check");
            if (CheckUser())
            {
                lnkbtn_editor.Enabled = true;
                lnkbtn_del.Enabled = true;
                lnkbtn_check.Enabled = true;
                lnkbtn_del.Attributes.Add("onClick", "javascript:return confirm('确定删除此记录？');");
            }
            else
            {
                lnkbtn_editor.Enabled = false;
                lnkbtn_check.Enabled = false;
                lnkbtn_del.Enabled = false;
            }
        }
    }
    private string GetSearch()
    {
        StringBuilder sbSearch = new StringBuilder();
        sbSearch.Append(_SQL_Catalog_Course);

        //获取所有课程状态为有效的课程
        //sbSearch.Append(" where ");
        string searchA = String.Format(" (Course_Id in (Select FkOID from TauthorityUser as a , TauthorityList as b where a. FkAuthorityID = b.FkAuthorityID and FkUserID ={0} and b.authorityType=4) or FkCourseCreatorid={0})", GetLoginEntity.UserID);
        if (ViewState["SearchType"].ToString() == "1")
        {
            sbSearch.Append(" 1=1 and ");
            if (!string.IsNullOrEmpty(txt_CourseName.Text))
            {
                sbSearch.Append(string.Format("CourseName like '%{0}%' and ", txt_CourseName.Text));
            }
            if (!string.IsNullOrEmpty(txt_CourseMostlyTeacherName.Text))
            {
                sbSearch.Append(string.Format("CourseMostlyTeacherName like '%{0}%' and ", txt_CourseMostlyTeacherName.Text));
            }
            //if (ddl_CourseState.SelectedValue.ToString() != "2")
            //{
            //    sbSearch.Append(string.Format("CourseState = {0} and ", ddl_CourseState.SelectedValue.ToString()));
            //}
            if (ddl_CourseType.SelectedValue.ToString() != "0")
            {
                sbSearch.Append(string.Format("CourseIsCompulsory = {0} and ", ddl_CourseType.SelectedValue.ToString()));
            }
            if (!string.IsNullOrEmpty(ddl_Catalog.SelectedValue.ToString()))
            {
                sbSearch.Append(string.Format("CatalogId = {0} and ", ddl_Catalog.SelectedValue.ToString()));
            }
            //如果是超级管理员登录可以查看所有课程
            if (GetLoginEntity.UserName.ToLower() != "admin" && GetLoginEntity.UserName.ToLower() != "administrator")
            {
                sbSearch.Append(searchA);
            }
        }
        else if (ViewState["SearchType"].ToString() == "0")//简单搜索
        {
            //如果是超级管理员登录可以查看所有课程
            if (GetLoginEntity.UserName.ToLower() == "admin" || GetLoginEntity.UserName.ToLower() == "administrator")
            {
                sbSearch.Append(string.Format(" (CourseName like '%{0}%' or CourseMostlyTeacherName like '%{0}%' or Description like '%{0}%') ", txt_SearchKey.Text));
            }
            else
            {
                sbSearch.Append(string.Format(" (CourseName like '%{0}%' and {1} or CourseMostlyTeacherName like '%{0}%' and {1} or Description like '%{0}%' and {1}) ", txt_SearchKey.Text, searchA));
            }
            
        }
        if (sbSearch.ToString().EndsWith(" and "))
            sbSearch.Remove(sbSearch.Length - 4, 4);

        return sbSearch.ToString();
    }

    private void BinderCatalog()
    {
        string search = "";
        //如果是超级管理员登录可以查看所有课程
        if (GetLoginEntity.UserName.ToLower() != "admin" && GetLoginEntity.UserName.ToLower() != "administrator")
        {
            search = String.Format("(CatalogID in (Select FkOID from TauthorityUser as a , TauthorityList as b where a. FkAuthorityID = b.FkAuthorityID and FkUserID ={0} and b.authorityType=3) or CreatorId={0})", GetLoginEntity.UserID);

        }
        DataTable dt = opCatalog.QueryCatalog(search);
        ArrayList list = opCatalog.GetCatalogTree(dt);
        opCatalog.GetCatalogTreeView(dt,ref tv_Catalog);

        ddl_Catalog.DataSource = list;
        ddl_Catalog.DataTextField = "Text";
        ddl_Catalog.DataValueField = "Value";
        ddl_Catalog.DataBind();
    }
    private void BinderPager(string search)
    {
        AspNetPager1.PageSize = LMSPageSize;
        AspNetPager1.RecordCount = opViewQuery.Count(search);
    }
    private void BinderRPT(string search,int pageIndex)
    {

        string orderList = ViewState["OrderList"].ToString();
        if (!string.IsNullOrEmpty(orderList))
            search += " order by " + orderList + ViewState["OrderType"].ToString();
        DataTable dt = opViewQuery.Query(search,LMSPageSize,pageIndex);
        rptCourse.DataSource = dt;
        rptCourse.DataBind();
        PreAspNetPager(AspNetPager1);

    }
    protected void btn_Search_Click(object sender, EventArgs e)
    {
        ViewState["SearchType"] = "1";
        string search = GetSearch();
        BinderPager(search);
        BinderRPT(search, 1);
    }
    protected void btn_Add_Click(object sender, EventArgs e)
    {
        string catalogid = "0";
        if (tv_Catalog.SelectedNode != null)
            catalogid = tv_Catalog.SelectedNode.Value.ToString();

        string url = "AddCourseInfo.aspx?CatalogID=" + catalogid;
        Script.RedirectURL(url);
    }
    protected void btnLock_Click(object sender, EventArgs e)
    {
        //冻结选中
        for (int i = 0; i < rptCourse.Items.Count; i++)
        {
            CheckBox cbox = (CheckBox)rptCourse.Items[i].FindControl("chkSelect");
            if (cbox.Checked)
            {
                Label lblid = (Label)rptCourse.Items[i].FindControl("lblid");
                VOTOCourse vo = opCourse.LoadVOTCourse(int.Parse(lblid.Text));
                if (vo != null)
                {
                    if (vo.CourseState != 0)
                    {
                        vo.CourseState = 0;
                        opCourse.UpdateCourse(vo);
                    }
                }
            }
        }
        chkAll.Checked = false;
        chkCancel.Checked = false;
        string search = GetSearch();
        BinderPager(search);
        BinderRPT(search, AspNetPager1.CurrentPageIndex);
       
    }
    protected void btnDel_Click(object sender, EventArgs e)
    {
        //删除选中
        for (int i = 0; i < rptCourse.Items.Count; i++)
        {
            CheckBox cbox = (CheckBox)rptCourse.Items[i].FindControl("chkSelect");
            if (cbox.Checked)
            {
                Label lblid = (Label)rptCourse.Items[i].FindControl("lblid");
                Label lbl_courseid = (Label)rptCourse.Items[i].FindControl("lbl_courseid");

                ////检查是否有方案引用
                //if (objProjectResource.QueryProjectResourceCount(" FKProresCourseID=" + lbl_courseid.Text) > 0)
                //{
                //    Script.Alert(this, "msg", "课程被方案引用，请先删除引用课程的方案");
                //    return;
                //}
                if (opCatalogCourse.DelCatalogCourse(int.Parse(lblid.Text)))
                {
                    string search1 = string.Format("FKCatalogcouCourseID = {0}", lbl_courseid.Text);
                    if (opCatalogCourse.QueryCatalogCourseCount(search1) == 0)
                    {
                        if (lbl_courseid.Text != "1")
                        {
                            if (lbl_courseid.Text != "1")
                            {
                                opCourse.DelCourse(int.Parse(lbl_courseid.Text));
                            }
                        }
                    }
                }
            }
        }
        string search = GetSearch();
        BinderPager(search);
        BinderRPT(search, AspNetPager1.CurrentPageIndex);
    }
    protected void chkAll_CheckedChanged(object sender, EventArgs e)
    {
        chkCancel.Checked = false;
        //全选 / 取消
        for (int i = 0; i < rptCourse.Items.Count; i++)
        {
            CheckBox cbox = (CheckBox)rptCourse.Items[i].FindControl("chkSelect");
            if (chkAll.Checked)
                cbox.Checked = true;
            else
                cbox.Checked = false;
        }
    }
    protected void chkCancel_CheckedChanged(object sender, EventArgs e)
    {
        chkAll.Checked = false;
        //反选
        for (int i = 0; i < rptCourse.Items.Count; i++)
        {
            CheckBox cbox = (CheckBox)rptCourse.Items[i].FindControl("chkSelect");
            if (cbox.Checked)
                cbox.Checked = false;
            else
                cbox.Checked = true;
        }
    }
    protected void btnAuditing_Click(object sender, EventArgs e)
    {
        //审核选中
        for (int i = 0; i < rptCourse.Items.Count; i++)
        {
            CheckBox cbox = (CheckBox)rptCourse.Items[i].FindControl("chkSelect");
            if (cbox.Checked)
            {
                Label lblid = (Label)rptCourse.Items[i].FindControl("lblid");
                VOTOCourse vo = opCourse.LoadVOTCourse(int.Parse(lblid.Text));
                if (vo != null)
                {
                    if (vo.CourseState != 1)
                    {
                        vo.CourseState = 1;
                        opCourse.UpdateCourse(vo);
                    }
                }
            }
        }
        chkAll.Checked = false;
        chkCancel.Checked = false;

        string search = GetSearch();
        BinderPager(search);
        BinderRPT(search, AspNetPager1.CurrentPageIndex);
    }
    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {
        string search = GetSearch();
        BinderRPT(search, AspNetPager1.CurrentPageIndex);
    }  
    protected void tv_Catalog_SelectedNodeChanged(object sender, EventArgs e)
    {
        ViewState["SearchType"] = "1";
        ddl_Catalog.SelectedValue = tv_Catalog.SelectedNode.Value.ToString();
        string search = GetSearch();
        BinderPager(search);
        BinderRPT(search, 1);
    }
    protected void btn_AddFKCourse_Click(object sender, EventArgs e)
    {
        string url = "CourseSelect.aspx?CatalogID=" + ddl_Catalog.SelectedValue.ToString();
        Script.RedirectURL(url);
    }
    protected void rptCourse_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName.ToLower() == "leditor")
        {
            string url = "EditCourseInfo.aspx?CourseID=" + e.CommandArgument.ToString();
            Script.RedirectURL(url);
        }
        else if (e.CommandName.ToLower() == "lscore")
        {
            string url = "ManageCoursePinion.aspx?type=0&CourseID=" + e.CommandArgument.ToString();
            Script.RedirectURL(url);
        }
        else if (e.CommandName.ToLower() == "ldel")
        {
            //if (IsLicensed("DelCourse"))
            //{


                PowerCreator.LMS.Course.Entity.VOTCatalogCourse voCatalogCourse = opCatalogCourse.LoadCatalogCourse(int.Parse(e.CommandArgument.ToString()));


                //检查是否有方案引用
                //if (objProjectResource.QueryProjectResourceCount(" FKProresCourseID=" + voCatalogCourse.FKCatalogcouCourseID) > 0)
                //{
                //    Script.Alert(this, "msg", "该课程被方案引用，请先删除引用该课程的方案");
                //    return;
                //}

                int CourseResourceCount = opCourse.QueryCourseResource(" FKCourseresCourseID=" + voCatalogCourse.FKCatalogcouCourseID).Rows.Count;
                if (CourseResourceCount > 0)
                {
                    Script.Alert(this, "msg", "请先删除课程资源");
                    return;
                }

                if (opCatalogCourse.DelCatalogCourse(voCatalogCourse.CatalogcouID))
                {
                    string search = string.Format("FKCatalogcouCourseID = {0}", voCatalogCourse.FKCatalogcouCourseID);
                    if (opCatalogCourse.QueryCatalogCourseCount(search) == 0)
                    {
                        if (voCatalogCourse.FKCatalogcouCourseID != 1)
                        {
                            if (voCatalogCourse.FKCatalogcouCourseID != 1)
                            {
                               
                               
                               opCourse.DelCourse(voCatalogCourse.FKCatalogcouCourseID);
                             
                                
                            }
                        }
                    }
                    //查看课程是否被多个专业引用，如果有多个专业，则删除该专业课程信息，如果只有一条记录，则删除该关系表的同时，删除课程信息表
                    search = GetSearch();
                    BinderPager(search);
                    BinderRPT(search, AspNetPager1.CurrentPageIndex);
                }
            //}
            //else
            //{
            //    Label lbl_msg = (Label)e.Item.FindControl("lbl_msg");
            //    lbl_msg.Text = GetLanageValueByKey("Course_msg_g1", PowerCreator.LMS.Language.LanagetItemType.Page);
            //}
        }
        else if (e.CommandName.ToLower() == "lcheck")
        {
            VOTOCourse vo = new VOTOCourse();
            vo = opCourse.LoadVOTCourse(int.Parse(e.CommandArgument.ToString()));
            if (vo.CourseState == 0)
                vo.CourseState = 1;
            else
                vo.CourseState = 0;
            opCourse.UpdateCourse(vo);
            //查看课程是否被多个专业引用，如果有多个专业，则删除该专业课程信息，如果只有一条记录，则删除该关系表的同时，删除课程信息表
            string search = GetSearch();
            BinderPager(search);
            BinderRPT(search, AspNetPager1.CurrentPageIndex);
        }
        else if (e.CommandName.ToLower() == "lrule")
        {
            string url = "../DL/Project/ManageRule.aspx?CourseID=" + e.CommandArgument.ToString();
            Script.RedirectURL(url);

        }
        else if (e.CommandName == "orderby")
        {
            ViewState["OrderList"] = e.CommandArgument.ToString();
            string search = GetSearch();
            BinderRPT(search, AspNetPager1.CurrentPageIndex);
            if (ViewState["OrderType"].ToString() == " desc")
                ViewState["OrderType"] = " asc";
            else
                ViewState["OrderType"] = " desc";
        }

    }
    protected void btn_SortSearch_Click(object sender, EventArgs e)
    {
        ViewState["SearchType"] = "0";
        string search = GetSearch();
        BinderPager(search);
        BinderRPT(search, AspNetPager1.CurrentPageIndex);
    }
}
